var $win = $(window);
var doc = window.document;
window.os = {
	config: {
		pwd: 'admin'
	},
	start: function() {
		if(LS.get('allowFullScreen') === undefined)
			LS.set('allowFullScreen', 'true');
		if (LS.get('booted') !== undefined) {
			this.login();
		} else {
			this.boot();
		}
		os.render();
	},
	changeTo: function(id, callback, delay) {
		delay = delay || 0;
		$('.osx .sence').removeClass('current');
		$('#' + id).addClass('current');
		window.setTimeout(function() {
			if ($.isFunction(callback))
				callback();
		}, delay);
	},
	init: {
		modernizr_test: function(){
			if (Modernizr.cssanimations) {
				$('#fail').remove();
			}
			else {
				$('#fail').addClass('visible');
			}
		},
		frame_breaker: function() {
			if (window.location !== window.top.location) {
				window.top.location = window.location;
			}
		},
		clock: function() {
			var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
			var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

			var newDate = new Date();
			newDate.setDate(newDate.getDate());
			$('#DateAbbr').html(dayNames[newDate.getDay()].substr(0,3) + " ");

			setInterval( function() {
				var minutes = new Date().getMinutes();
				$(".min, .mins").html(( minutes < 10 ? "0" : "" ) + minutes);
				},1000);

			setInterval( function() {
				var hours = new Date().getHours();
				$(".hours, .hour").html(( hours < 10 ? "0" : "" ) + hours);
			}, 1000);
		},
		desktop: function() {
			var apps = [
				{
					title: '关于本系统',
					icon: 'finder.png',
					link: '#about-this-mac',
					width: '287',
					height: '338'
					// win_title: ,
				},
				{
					title: '百度',
					icon: 'baidu.png',
					link: 'http://www.baidu.com',
					width: '740',
					height: '300',
					win_title: '百度'
				},
				{
					title: '豆瓣电台',
					icon: 'douban.png',
					link: 'http://douban.fm/partner/qq_plus',
					width: '545',
					height: '460',
					win_title: '豆瓣电台'
				},
				{
					title: 'ascii流程图',
					icon: 'ascii_flow.png',
					link: 'http://asciiflow.com',
					width: '1000',
					height: '700',
					win_title: 'ascii流程图'
				},
				{
					title: '五子棋',
					icon: 'gomoku.png',
					link: 'http://www.html5tricks.com/demo/wuziqi/game.html',
					width: '1000',
					height: '700',
					win_title: '五子棋'
				}

			];

			for (var i = 0; i < apps.length; i++) {
				$('#container1').append([
					'<div class="icon" data-target="'+apps[i].link+'" data-width="'+apps[i].width+'" data-height="'+apps[i].height+'" data-title="'+apps[i].title+'">',
						'<img src="assets/img/icons/'+apps[i].icon+'" height="90">',
						'<span class="white icon-title">'+apps[i].title+'</span>',
					'</div>'
					].join('')
				);
			};
			// os.desktop.appMenu();
			var d = $(document);
			// Cancel mousedown.
			d.mousedown(function(ev) {
				var tags = ['div', 'document', 'button', 'a','input', 'select', 'textarea', 'tr', 'li'].join(',');

				if (!$(ev.target).closest(tags).length) {
					if(ev.target.tagName == 'BODY'){
						$('.am-modal.am-modal-active').hide();
					}
					os.desktop.clear_active();
					ev.preventDefault();
					ev.stopPropagation();
				}
			});
			// Cancel right-click.
			d.on('contextmenu', '#page',function() {
				// return false;
			});

			d.on('click', '#menu li a', function(ev) {
				var $current_li = $(this).parent();
				var index = $current_li.index();
				if(index >0){
					$('#menu li').removeClass('here');
					$current_li.addClass('here');
					$('section.container').addClass('hidden');
					$('#container'+index).removeClass('hidden');
					if(index != 1){
						$('.dock').hide();
					}else{
						$('.dock').show();
					}
				}
			});

			d.on('click', 'a', function(ev) {
				var url = $(this).attr('href');
				this.blur();
				console.log(ev);
				if (url.match(/^#/)) {

					ev.preventDefault();
					ev.stopPropagation();
				} else {
					$(this).attr('target', '_blank');
				}
			});

			// Cancel single-click.
			d.on('mousedown', 'div.icon', function() {
				// Highlight the icon.
				// os.desktop.clear_active();
				$(this).addClass('active');
			});

			// Respond to double-click.
			d.on('dblclick', 'div.icon', function() {
				var $app = $(this);
                var $attr = $app.data();
                var has_iframe = false;
                var x = $attr.target;

                var win_content;
                var index = $app.index();
                var icon_src = $(this).find('img:eq(0)').attr('src');

                if (x.indexOf('#') == -1) {
                    var iframe_width = '100%';
                    var iframe_height = '100%';
                    has_iframe = true;
                }
                if ($attr.width && $attr.height) {
                    iframe_width = $attr.width+'px';
                    iframe_height = $attr.height;
                }

                var title = $attr.title || false;
                var templateUrl = './view/app.html';

                if($app.attr('opened') == undefined){
                    var $appMenuUl = $('#appMenu ul');
                    var config = {
                        title: title,
                        maxmin: true,
                        fix : false,
                        shade : [false],
                        loading: {type: 3},
                        border : [false],
                        min: function(layer){
                            $(layer).hide();
                        },
                        restore: function(layer){

                        },
                        success: function(openedlayer){
                            var win_id = $(openedlayer).attr('id');
                            $app.attr('opened', win_id);
                            layer.setTop(openedlayer);
                            $appMenuUl.append([
                                '<li>',
                                '<a href="' + win_id + '" title="' + title + '">',
                                '<img src="' + icon_src + '" alt="" />',
                                '</a>',
                                '</li>'
                            ].join(''));
                            os.desktop.appMenu_getIds();
                        }, //创建成功后的回调
                        close: function(index){
                            layer.close(index);
                            $app.removeAttr('opened');
                            $appMenuUl.find('li a[href="xubox_layer' + index + '"]').parent().remove();
                            os.desktop.appMenu_getIds();
                        }, //右上角关闭回调
                        end: function(){} //终极销毁回调
                    }
                    if(has_iframe){
                        config.type = 2;
                        config.shadeClose = false;
                        config.area = [iframe_width, iframe_height];
                        config.iframe = {
                            src : x
                        };
                    }else{
                        config.title = '测试title';
                        config.type = 1;
                        // config.maxmin = false;
                        config.page = {dom: x, html: $(x).html(), url: ''};
                    }
                    console.log(config);

                    var openedlayer = $.layer(config);
                }else{
                    var id = $app.attr('opened');
                    var $win = $('#'+id);
                    var layer_index = id.replace('xubox_layer','');
                    if($win.css('display') == 'none'){
                        $win.show();
                        layer.restore(layer_index);
                    }else{
                        $win.trigger('mousedown');
                    }
                }
			});
			// Fix Classes after Validate Login
			$('.submit').click(function() {
				var ValPassword = $('#password').val() === 'admin';
				if (ValPassword === true) {
					$('input[type=password]').addClass('valid');
					$('.tooltip-pass').hide();
					$('.submit').removeClass('submit').addClass('charge');
					$('#pageLogin').addClass('initLog').delay(1900).queue(function() { $(this).removeClass('initLog').addClass('initLogExit'); $(this).dequeue(); });;
					$('#page, #head').delay(2500).queue(function() { $(this).addClass('vis'); $(this).dequeue(); });
					$('.window').delay(3000).queue(function() { $(this).addClass('windows-vis'); $(this).dequeue(); });
					event.preventDefault();
					LS.set('logged',true);
				}
				else {
					$('.tooltip-pass').hide();
					$('input[type=password]').select();
					$('.validate').addClass('error').delay(210).queue(function() {
						$(this).removeClass('error');
						$(this).dequeue();
						$('.tooltip-pass').show();
					});
					return false;
				}
			});
		},
		dock: function() {
			$('.dock ul li').hover(
				function(){
					$(this).addClass('ok').prev().addClass('prev').prev().addClass('prev-ancor');
					$(this).addClass('ok').next().addClass('next').next().addClass('next-ancor');
				},
				function(){
					$('.dock ul li').removeClass('ok prev next next-ancor prev-ancor');
				}
			);
		},
		resize :function(){
			$(window).on('resize', function(){
				os.desktop.autoWidth();
				os.desktop.autoHeight();
			});
		},
	},
	render: function() {
		for (var i in os.init) {
			os.init[i]();
		}
	},
	desktop: {
		appMenu: function() {
			$('#appMenu').appMenu({
		        reorder: false,
		        showControl: true,
		        // debug:       true,
		        showControlText : '用alt+tab 切换已经打开的应用',
		        updateHash: false,
		        onSelect: function(obj, options) {
		            var itemTarget = obj;
		            $('div[opened="'+obj+'"]').trigger('dblclick');
		        }
    		});
		},
		appMenu_getIds: function() {
			var items = $('#appMenu').find('ul li a'),
					itemsNum = items.length;

			// Cycle through items, updating the IDs:
			var i = 0;
			items.each(function() {
				$(this).attr('id', 'item-' + i);
				i++;
			});
		},
		clear_active: function() {

		},
		getSize:function(){
			var winHeight, winWidth;
			//获取窗口宽度
			if (window.innerWidth)
				winWidth = window.innerWidth;
			else if ((document.body) && (document.body.clientWidth))
				winWidth = document.body.clientWidth;
			//获取窗口高度
			if (window.innerHeight)
				winHeight = window.innerHeight;
			else if ((document.body) && (document.body.clientHeight))
				winHeight = document.body.clientHeight;
			//通过深入Document内部对body进行检测，获取窗口大小
			if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth){
				winHeight = document.documentElement.clientHeight;
				winWidth = document.documentElement.clientWidth;
			}
			return {
				width: winWidth,height: winHeight
			};
		},
		autoWidth: function(){
			// var size = os.desktop.getSize();
			// $('.osx .sence').width(size.width+'px');
		},
		autoHeight: function() {
			var size = os.desktop.getSize();
			$('section iframe').height((size.height - 22)+'px');
		},
		wallpaper: function(e) {
			// $('#' + e).css('background-image', 'url(assets/img/Galaxy.jpg)');
		}
	},
	boot: function() {
		this.changeTo('pageLoading', function() {
			$('#startSound')[0].play();
			window.setTimeout(function() {
				LS.set('booted', true);
				os.login();
			}, 2000);

		}, 2000);
	},
	login: function() {
		if (LS.get('logged'))
			this.changeTo('page', function() {
				// $('#pageLogin').addClass('initLog').delay(1900).queue(function() { $(this).removeClass('initLog').addClass('initLogExit'); $(this).dequeue(); });;
				$('#page, #head').delay(0).queue(function() { $(this).addClass('vis'); $(this).dequeue(); });
				$('.window').delay(0).queue(function() { $(this).addClass('windows-vis'); $(this).dequeue(); });
				os.desktop.autoHeight();
				os.desktop.wallpaper('desktop_content');

				os.desktop.appMenu();
				//-----------------------------------------------------------------------------------
				//	5.	Hide and Close
				//-----------------------------------------------------------------------------------
				var left = 50 + '%';
				var top = 15 + '%';
				var item = $('<div class="fresh"></div>').hide();
				var itemR = $('<div class="fresh"></div>').hide();

				$("a[data-rel=close]").click(function(e) {
					e.preventDefault();
					$(this.hash).fadeOut(200, function() {
						$(this).css({ top: top, left: left });
					});
				});

				$("a[data-rel=show]").click(function(e) {
					e.preventDefault();
					$(this.hash).show();
				});

				$(".dock li a[data-rel=showOp]").click(function(e) {
					e.preventDefault();
					$(this).addClass('bounce').delay(1600).queue(function() {
						alert('尚未实现功能');
						$(this).removeClass('bounce');
						$(this).dequeue();
					});
				});

				$(".dock li a[data-rel=showOpTrash]").click(function(e) {
					e.preventDefault();
					$(this).addClass('bounce').delay(1600).queue(function() { $(this).removeClass('bounce'); $(this).append(itemR); itemR.fadeIn(500); $(this).dequeue(); });
					$("#trash").delay(1630).queue(function() { $(this).show(); $(this).dequeue(); });
				});

				$('#logout').click(function(){
					os.logout();
				});
				$('#shutdown').click(function(){
					os.shoutdown();
				});
			});
		else{

			// $('#login .am-container').height((doc.body.scrollHeight) + 'px');
			this.changeTo('pageLogin', function() {
				$('#page').removeClass('vis');
				$("a[data-rel=show]").click(function(e) {
					e.preventDefault();
					$(this.hash).show();
				});

			});
		}
	},
	logout: function() {
		LS.remove('logged');
		os.login();
	},
	shoutdown: function() {
		LS.remove('booted');
		os.logout();
		os.boot();
	}
};

$(document).ready(function() {
	os.start();
});
